import _ from 'lodash-es';

const DOC = window.document;

function createDrag ({
  onDragStart = _.noop,
  onDraging = _.noop,
  onDragEnd = _.noop,
}) {

  let isDraging = false;
  let startX = 0;
  let startY = 0;

  function handleMouseMove(e) {
    if (!isDraging) return;

    const deltaX = e.x - startX;
    const deltaY = e.y - startY;

    startX = e.x;
    startY = e.y;

    return onDraging({ deltaX, deltaY, event: e });
  }

  function handleMouseUp(e) {
    isDraging = false;

    DOC.removeEventListener('mousemove', handleMouseMove, false);
    DOC.removeEventListener('mouseup', handleMouseUp, false);
    return onDragEnd({ event: e });
  }

  function handleMouseDown(e) {
    isDraging = true;
    startX = e.x;
    startY = e.y;

    DOC.addEventListener('mousemove', handleMouseMove, false);
    DOC.addEventListener('mouseup', handleMouseUp, false);
    return onDragStart({ startX, startY, event: e });
  }

  return handleMouseDown;
}

export {
  createDrag,
};
